<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','getuserInfo'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }
    public  function request($url, $params)
    {
        $ch = curl_init();

//$this_header = array("content-type: application/x-www-form-urlencoded;charset=UTF-8");

        $this_header = array('Content-Type: application/json; charset=utf-8');

        curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');

        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        curl_setopt($ch, CURLOPT_POST, 1);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//如果不加验证,就设false,商户自行处理

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }

    public function getuserInfo($code=''){
        if($code==''){
            $this->error('Code获取失败');
        }
        $result=getaccess_token();

        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            $access_token=$json['access_token'];
        }else{
            $this->error("授权失败," . $result['msg']);
        }
        $url="https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=".$access_token."&code=".$code;
        $message=  (array)json_decode($this->request($url,[]), true); // 获得用户userid
        $userurl="https://qyapi.weixin.qq.com/cgi-bin/auth/getuserdetail?access_token=".$access_token;
        $json_data = json_encode(['user_ticket'=>$message['user_ticket']]);
        $userInfo=  (array)json_decode($this->request($userurl,$json_data), true); // 获得用户
        $userurl1="https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=".$access_token."&userid=".$message['userid'];
        $userInfo1=  (array)json_decode($this->request($userurl1,[]), true); // 获得用户
        if($userInfo['userid']){
            $user = \app\common\model\User::getByUserid($userInfo['userid']);
            if ($user) {
                if ($user->status != 'normal') {
                    $this->error(__('账户被锁定，请联系管理员'));
                }
                $user = $this->auth->getUser();
                $user->avatar = $userInfo['avatar'];
                $user->save();

                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
            } else {
                $ret = $this->auth->register($userInfo['userid'],$userInfo1['name'], Random::alnum(), '', $userInfo['mobile'],
                    ['avatar'=>$userInfo['avatar'],'gender'=>$userInfo['avatar'],'email'=>$userInfo['email'],
                        'qr_code'=>$userInfo['qr_code'],'biz_mail'=>$userInfo['biz_mail'],'address'=>$userInfo['address'],'user_ticket'=>$message['user_ticket']
                    ,'department_ids'=>explode(",",$userInfo1['department'])]);
            }
            if ($ret) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('登陆成功'), $data);
            } else {
                $this->error($this->auth->getError());
            }
        }

        $this->success('ok',$userInfo);
    }



    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('ok',$this->auth->getUserinfo());
    }





    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        if($this->request->post('username')){
            $username = $this->request->post('username');
            $user->username = $username;
        }

        if($this->request->post('avatar')){
            $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
            $user->avatar = $avatar;
        }
        $user->save();
        $this->success();
    }


}
